package com.gopay.bis.manager.bank.Wap;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.gdb.ebank.GdbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.WapPayManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

/**
 * 广发wapB2C网关支付对象封装
 * 
 * @GdbWapB2cManager.java
 * @author lilili
 * @2017-03-07 下午3:28:21 www.gopay.com.cn Inc.All rights reserved.
 */
public class GdbWapB2cManager implements WapPayManagerRemoteService {

	@Resource(name = "gdbWapBankServiceClient")
	private BankService gdbWapBankServiceClient;

	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		GdbB2cMessage messageB2C = new GdbB2cMessage();
		msg.setBankOrderId(msg.getOrderId());
		BeanUtils.copyProperties(msg, messageB2C);
		// 组装签名明文(merId|orderNum|orderAmt|orderDate|orderTime)
		String plainMessage = buildPlainB2C(msg);
		messageB2C.setPlainMessage(plainMessage);
		BankLogUtils.printB2CManagerSignSendLog(messageB2C);
		// 调用远程接口请求签名数据
		String payUrl = (String) gdbWapBankServiceClient.sign(messageB2C);
		messageB2C.setPayUrl(payUrl);
		BankLogUtils.printB2CManagerSignReturnLog(messageB2C);
		return messageB2C;
	}

	/**
	 * 构建B2C报文
	 * 
	 * @param message
	 *            广发银行wapB2C数据结构体
	 * @return String 商户签名源数据
	 */
	public String buildPlainB2C(BaseMessage message) {
		StringBuffer sb = new StringBuffer("");
		Date date = new Date();
		String newDate = TransUtil.getDateStr("yyyyMMddHHmmss", date);
		String orderDate = newDate.substring(0, 8);
		String orderTime = newDate.substring(8);
		sb.append(message.getMerID()).append("|").append(message.getBankOrderId()).append("|").append(message.getAmount()).append("|").append(orderDate).append("|")
				.append(orderTime);
		return sb.toString();
	}

	@Override
	public Object verify(BaseMessage msg) throws GopayException {
		BankLogUtils.printB2CVerifyPlainLog(msg);
		BankLogUtils.printB2CVerifySignatureLog(msg, msg.getSignMessage());
		boolean isVerify;
		isVerify = (Boolean) this.gdbWapBankServiceClient.verify(msg);
		BankLogUtils.printB2CVerifyResultLog(msg, isVerify);
		return isVerify;
	}

	@Override
	public Object query(Object msg) throws GopayException {
		GdbB2cMessage messageB2C = (GdbB2cMessage) msg;
		// 组装签名明文(订单号+商户号)
		String plainMessage = messageB2C.getBankOrderId() + "||" + messageB2C.getMerID() + "||";
		messageB2C.setPlainMessage(plainMessage);

		BankLogUtils.printB2CManagerQuerySendLog(messageB2C, "");
		messageB2C = (GdbB2cMessage) this.gdbWapBankServiceClient.query(messageB2C);

		BankLogUtils.printB2CManagerQueryReturnLog(messageB2C);
		return messageB2C;
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
